package com.dbapp.config;

import com.dbapp.common.exception.BussinessException;
import com.dbapp.common.response.Result;
import com.dbapp.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description: 异常包装
 * @author: weiyi.liu
 * @date: 2023-05-15 14:57
 */

@RestControllerAdvice(basePackages = "com.dbapp")
@Slf4j
public class GlobalExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseBody
    public Result handleException(BussinessException e) {
        log.error("BussinessException:{}",e);
        if(StringUtils.isNotEmpty(e.getRedirectUrl())){
            return Result.error(e.getRedirectUrl(),e.getCode(), e.getMessage());
        }
        return Result.error(e.getCode(), e.getMessage());
    }


    /**
     * 处理所有不可知的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultException( Exception e) {
        //输出堆栈信息到控制台，以后记录到日志
        LOG.error("defaultException:{}", e);
        return Result.error(500,e.getMessage());
    }

}
